﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

using Utils;

namespace System.Linq
{
    public static class IEnumerableHelper
    {

        /// <summary>
        /// 差集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="KEY"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="commp"></param>
        /// <returns></returns>
        public static IEnumerable<T> ExceptBy<T, KEY>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, KEY> commp)
        {
            return first.Except(second, new DefaultEqualityComparer<T, KEY>(commp));
        }
        /// <summary>
        /// 并集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="KEY"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="commp"></param>
        /// <returns></returns>
        public static IEnumerable<T> UnionBy<T, KEY>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, KEY> commp)
        {
            return first.Union(second, new DefaultEqualityComparer<T, KEY>(commp));
        }
        /// <summary>
        /// 交集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="KEY"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="commp"></param>
        /// <returns></returns>
        public static IEnumerable<T> IntersectBy<T, KEY>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, KEY> commp)
        {
            return first.Intersect(second, new DefaultEqualityComparer<T, KEY>(commp));
        }
        /// <summary>
        /// 去重
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="KEY"></typeparam>
        /// <param name="first"></param>
        /// <param name="commp"></param>
        /// <returns></returns>
        public static IEnumerable<T> DistinctBy<T, KEY>(this IEnumerable<T> first, Func<T, KEY> commp)
        {
            return first.Distinct(new DefaultEqualityComparer<T, KEY>(commp));
        }


        /// <summary>
        /// 数组遍历
        /// </summary>
        /// <param name="end"></param>
        /// <returns></returns>
        public static IEnumerable<int> Range(this int end)
        {
            for (int i = 0; i < end; i++)
            {
                yield return i;
            }
            yield break;
        }

        public static IEnumerable<int> Range(this int start, int end)
        {
            for (int i = start; i < end; i++)
            {
                yield return i;
            }
            yield break;
        }

        public static async Task<List<T>> ToTaskList<T>(this IAsyncEnumerable<T> list)
        {
            List<T> result = new List<T>();
            await foreach (var item in list)
            {
                result.Add(item);
            }
            return result;
        }
        /// <summary>
        /// 集合中是否包含满足条件的某项
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="list">集合对象</param>
        /// <param name="predicate">判定条件</param>
        /// <returns>是否存在</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     List<string> list={"1","3","5","7"};
        ///     
        ///     bool ret=list.Contains(c=>c=="3");  //True
        /// ]]>
        /// </code>
        /// </example>
        public static bool Contains<T>(this IEnumerable<T> list, Predicate<T> predicate)
        {
            return list.Any(item => predicate(item));
        }

        /// <summary>
        /// 对IEnumerable&lt;T&gt;的每个元素执行指定操作
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="list">集合对象</param>
        /// <param name="action">要执行的操作</param>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     string[] list={"1","3","5","7"};
        ///     list.ForEach(c=>{
        ///         Response.Write(c);
        ///     });
        /// ]]>
        /// </code>
        /// </example>
        public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
        {
            foreach (T item in list)
            {
                action(item);
            }
        }

        public static IEnumerable<T> TrueThrow<T>(this IEnumerable<T> list, Predicate<T> predicate, Func<T, Exception> funcException)
        {
            foreach (T item in list)
            {
                if (predicate(item))
                {
                    throw funcException(item);
                }
            }
            return list;
        }
        /// <summary>
        /// 递归节点
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="current"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static List<T> Recursion<T>(this IEnumerable<T> current, Func<T, IEnumerable<T>> expression) where T : Recursion<T>
        {
            var list = current.ToList();
            list.ForEach(p =>
            {
                p.Nodes = Recursion(expression(p), expression);
            });
            return list;
        }
        /// <summary>
        ///  在指定  IEnumerable`T 的每个元素之间串联指定的分隔符 System.String，从而产生单个串联的字符串。
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="list">集合对象</param>
        /// <param name="toText">将T转换为文本</param>
        /// <param name="separator">分隔符</param>
        /// <returns>拼接字符串</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     List<DateTime> list=new List<DateTime>();
        ///     
        ///     string ret=list.Join(d=>d.ToString("yyyyMMdd"),",");
        /// 
        /// ]]>
        /// </code>
        /// </example>
        public static string Join<T>(this IEnumerable<T> list, Func<T, string> toText, string separator)
        {
            if (list == null)
                return null;

            StringBuilder sb = new StringBuilder();
            var enumtor = list.GetEnumerator();
            if (enumtor.MoveNext())
            {
                sb.Append(toText(enumtor.Current));
                while (enumtor.MoveNext())
                {
                    sb.Append(separator);
                    sb.Append(toText(enumtor.Current));
                }
            }

            return sb.ToString();
        }


        /// <summary>
        /// 在指定  IEnumerable`T 的每个元素之间串联指定的分隔符 System.String，从而产生单个串联的字符串。
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="list">集合对象</param>
        /// <param name="separator">分割字符</param>
        /// <returns>拼接字符串</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     int[] ary={1,2,3,4,5};
        ///     
        ///     string str=ary.Join();  //返回："1,2,3,4,5"
        /// ]]>
        /// </code>
        /// </example>
        public static string Join<T>(this IEnumerable<T> list, string separator = ",")
        {
            if (list == null)
                return null;

            return list.Join((T v) => v.ToString(), separator);
        }



        public static void PaddingName<T, K, V>(this List<T> list, Func<Dictionary<K, V>> createDict, Func<T, K> from, Expression<Func<T, V>> selector)
        {
            if (list.Count == 0) return;
            var dict = createDict();
            PropertyInfo info = (selector.Body as MemberExpression).Member as PropertyInfo;
            foreach (var item in list)
            {
                info.SetValue(item, dict.TryGetValue(from(item), default));
            }
        }
    }

    public interface Recursion<T>
    {
        List<T> Nodes { get; set; }

    }
}
